<template>
  <el-dialog :model-value="visible" @update:model-value="$emit('update:visible', $event)" title="新增仪器" width="500px">
    <el-form :model="form" :rules="rules" label-width="100px" ref="formRef">
      <el-form-item label="仪器名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="仪器房间" prop="roomId">
        <el-input-number v-model="form.roomId" :min="1" />
      </el-form-item>

      <el-form-item label="仪器类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择类型">
          <el-option label="科研实验室" value="1" />
          <el-option label="教学实验室" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="子类型" prop="subType">
        <el-select v-model="form.subType" placeholder="请选择子类型">
          <el-option
              v-for="item in subTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="可被预约">
        <el-switch v-model="form.isAvailable" />
      </el-form-item>

      <el-form-item label="积分消耗" prop="pointsCost">
        <el-input-number v-model="form.pointsCost" :min="0" />
      </el-form-item>

      <el-form-item label="照片" prop="imgName">
        <el-upload
            :auto-upload="false"
            :limit="1"
            :on-change="handleImageChange"
            list-type="picture-card"
            :file-list="uploadFileList"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>


    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" @click="submit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createInstrument } from "@/apps/admin/utils/instrumentApi.js";
import request from "@/apps/admin/utils/request.js";

const props = defineProps({
  visible: Boolean,
  instrumentData: Object
})
const uploadFileList = ref([])
const rules = {
  name: [
    { required: true, message: '请输入仪器名称', trigger: 'blur' },
    { min: 1, max: 16, message: '名称长度在1-16字符之间', trigger: 'blur' }
  ],
  roomId: [
    { required: true, message: '请输入房间号', type: 'number', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  subType: [
    { required: true, message: '请选择子类型', trigger: 'change' }
  ],
  pointsCost: [
    { required: true, message: '请输入积分', type: 'number', trigger: 'blur' },
    { type: 'number', min: 0, message: '积分不能为负数', trigger: 'blur' }
  ],
  imgName: [
    { required: true, message: '请上传图片', trigger: 'change' }
  ]
}

const emit = defineEmits(['update:visible', 'submit'])
const subTypes = JSON.parse(sessionStorage.getItem("instrumentSubTypes"));

const formRef = ref()
const form = ref({
  roomId: null,
  type: '',
  subType: '',
  isAvailable: true,
  pointsCost: 0,
  imgName: ''
})
if (props.instrumentData.imgName) {
  uploadFileList.value = [
    {
      name: form.value.imgName,
      url: "/api/src/img/" + form.value.imgName,
      status: 'finished',
      uid: '-1'
    }
  ]
} else {
  uploadFileList.value = []
}
// 图片处理
const handleImageChange = async (uploadFile) => {
  const file = uploadFile.raw;

  if (file.size > 512 * 1024) {
    ElMessage.error("图片大小不能超过 512KB");
    return;
  }

  try {
    const formData = new FormData();
    formData.append('file', file);

    const res = await request.post('/v1/admin/uploadImg', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });

    const url = res.data.url;
    if (url) {
      form.value.imgName = url;
    } else {
      ElMessage.error("上传失败");
    }

  } catch (err) {
    ElMessage.error("图片上传失败");
  }
};

const submit = () => {
  formRef.value.validate((valid) => {
    if (!valid) return

    createInstrument(form.value).then((body) => {
      if (body.code === 200) {
        ElMessage.success("创建成功")
        formRef.value = ref()
        emit('update:visible', false)
      } else {
        ElMessage.error(body.msg)
      }
    }).catch((error) => {
      ElMessage.error(error?.response?.data?.msg || '请求失败')
    })
  })
}

</script>
